'use client';

import React, { useState, useEffect } from 'react';
import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { signOut, useSession } from 'next-auth/react';
import {
  HomeIcon,
  ChartBarIcon,
  UserIcon,
  BellIcon,
  Cog6ToothIcon,
  DocumentDuplicateIcon,
  ClipboardDocumentListIcon,
  ArrowRightOnRectangleIcon,
} from '@heroicons/react/24/outline';
import NotificationDropdown from '@/components/notification/notification-dropdown';
import useBreakpoint from '@/hooks/use-breakpoint';
import { cn } from '@/lib/utils';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';

const navigation = [
  { name: '首页', href: '/dashboard', icon: HomeIcon },
  { name: '项目', href: '/project', icon: DocumentDuplicateIcon },
  { name: '任务', href: '/task', icon: ClipboardDocumentListIcon },
  { name: '统计', href: '/stats', icon: ChartBarIcon },
];

export default function Navbar() {
  const { data: session, status } = useSession();
  const isAuthenticated = status === 'authenticated';
  const pathname = usePathname();
  const { isMobile } = useBreakpoint();
  const [showUserMenu, setShowUserMenu] = useState(false);

  // 点击页面其他区域时关闭用户菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const userMenuButton = document.getElementById('user-menu-button');
      const userMenu = document.getElementById('user-menu');
      
      if (
        userMenuButton && 
        userMenu && 
        !userMenuButton.contains(event.target as Node) && 
        !userMenu.contains(event.target as Node)
      ) {
        setShowUserMenu(false);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  // 处理登出
  const handleSignOut = () => {
    signOut({ callbackUrl: '/' });
  };

  return (
    <nav className="bg-white shadow-sm border-b border-gray-200">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between h-16">
          <div className="flex">
            {/* Logo */}
            <div className="flex-shrink-0 flex items-center">
              <Link href="/dashboard" className="text-xl font-bold text-[var(--primary-color)]">
                NextCollab
              </Link>
            </div>
            
            {/* 主导航链接 */}
            <div className="hidden md:ml-6 md:flex md:items-center md:space-x-4">
              {navigation.map((item) => (
                <Link
                  key={item.name}
                  href={item.href}
                  className={cn(
                    pathname === item.href || pathname.startsWith(`${item.href}/`)
                      ? 'bg-[var(--primary-color)] text-white'
                      : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900',
                    'px-3 py-2 rounded-md text-sm font-medium flex items-center'
                  )}
                >
                  <item.icon className="h-5 w-5 mr-1.5" aria-hidden="true" />
                  {item.name}
                </Link>
              ))}
            </div>
          </div>
          
          {/* 右侧用户菜单和通知 */}
          <div className="flex items-center">
            {isAuthenticated && (
              <>
                {/* 通知图标 - 仅在非移动设备上显示 */}
                {!isMobile && <NotificationDropdown />}
                
                {/* 用户资料下拉菜单 */}
                <div className="ml-3 relative">
                  <div>
                    <button
                      type="button"
                      className="flex rounded-full bg-white text-sm focus:outline-none focus:ring-2 focus:ring-[var(--primary-color)] focus:ring-offset-2"
                      id="user-menu-button"
                      aria-haspopup="true"
                      onClick={() => setShowUserMenu(!showUserMenu)}
                    >
                      <span className="sr-only">打开用户菜单</span>
                      <Avatar size={32}>
                        <AvatarImage 
                          src={session?.user?.image || undefined} 
                          alt={session?.user?.name || "用户"} 
                        />
                        <AvatarFallback>
                          {session?.user?.name ? session.user.name.charAt(0).toUpperCase() : '?'}
                        </AvatarFallback>
                      </Avatar>
                    </button>
                  </div>
                  
                  {/* 用户下拉菜单 */}
                  {showUserMenu && (
                    <div
                      id="user-menu"
                      className="absolute right-0 z-50 mt-2 w-48 origin-top-right rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none animate-slideUp"
                      role="menu"
                      aria-orientation="vertical"
                      aria-labelledby="user-menu-button"
                      tabIndex={-1}
                    >
                      <Link
                        href="/profile"
                        className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                        role="menuitem"
                        tabIndex={-1}
                        onClick={() => setShowUserMenu(false)}
                      >
                        <div className="flex items-center">
                          <UserIcon className="mr-2 h-4 w-4" />
                          个人资料
                        </div>
                      </Link>
                      <Link
                        href="/settings"
                        className="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                        role="menuitem"
                        tabIndex={-1}
                        onClick={() => setShowUserMenu(false)}
                      >
                        <div className="flex items-center">
                          <Cog6ToothIcon className="mr-2 h-4 w-4" />
                          设置
                        </div>
                      </Link>
                      <button
                        className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                        role="menuitem"
                        tabIndex={-1}
                        onClick={handleSignOut}
                      >
                        <div className="flex items-center text-red-600">
                          <ArrowRightOnRectangleIcon className="mr-2 h-4 w-4" />
                          退出登录
                        </div>
                      </button>
                    </div>
                  )}
                </div>
              </>
            )}
            
            {/* 未登录状态显示登录按钮 */}
            {!isAuthenticated && !pathname.startsWith('/auth/') && (
              <Link
                href="/auth/login"
                className="ml-3 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-[var(--primary-color)] hover:bg-[var(--primary-hover)] focus:outline-none"
              >
                登录
              </Link>
            )}
          </div>
        </div>
      </div>
    </nav>
  );
} 